package org.easymis.crm.modules.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.easymis.commons.web.BaseController;
import org.easymis.commons.web.annotation.SysLog;
import org.easymis.commons.web.utils.Json;
import org.easymis.commons.web.utils.VrifyCodeUtil;
import org.easymis.crm.config.SystemConstant;
import org.easymis.crm.modules.system.entitys.mybatis.dto.HrmStaffInfo;
import org.easymis.crm.modules.system.entitys.mybatis.dto.Member;
import org.easymis.crm.modules.system.service.HrmStaffInfoMng;
import org.easymis.crm.modules.system.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


/**
 * @description 登录操作的控制类，使用Shiro框架，做好了登录的权限安全认证，
 *              getRemortIP()方法获取用户登录时的ip并保存到数据库，使用Redis实现缓存
 * 
 */
@Api(tags = "平台登录操作")
@Controller
public class LoginController extends BaseController {
	@Autowired
	MemberService memberService;
	@Autowired
	HrmStaffInfoMng staffInfoMng;
	/**
	 * 获取登录用户的IP
	 * 
	 * @throws Exception
	 */
	public void getRemortIP(String username) {
		HttpServletRequest request = this.getRequest();
		Map<String, String> map = new HashMap<String, String>();
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {
			ip = request.getRemoteAddr();
		} else {
			ip = request.getHeader("x-forwarded-for");
		}
		map.put("username", username);
		map.put("loginIp", ip);
		memberService.saveIp(map);
	}
	/**
	 * 访问后台登录页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value="跳转登录页面", notes="跳转登录页面")
	@SysLog("跳转登陸页面")
	@RequestMapping(value = "/login", method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
	public ModelAndView toLogin() throws ClassNotFoundException {
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("login");
		return mv;
	}
    @ApiOperation(value = "登录系统 ",notes = "",produces = MediaType.ALL_VALUE)
    @ApiImplicitParams({ @ApiImplicitParam(name = "username",value = "帐号",dataType = "java.lang.String",required = true), @ApiImplicitParam(name = "password",value = "密码",dataType = "java.lang.String",required = true) })
    @ResponseBody
    @RequestMapping(value = "/common/login_do/login.do",method = { RequestMethod.GET, RequestMethod.POST })
    public Json login(HttpServletRequest httpServletRequest,ModelMap map) throws Exception{
        // 首先检测验证码
        Json json = new Json();
        json.setSuccess(false);
        if (!VrifyCodeUtil.checkvrifyCode(httpServletRequest, map)) {
            json.setMsg("验证码不正确");
            return json;
        }
        String username = getStringParamDefaultBlank(httpServletRequest, "username");
        String password = getStringParamDefaultBlank(httpServletRequest, "password");
//        Loginproxy proxy = LoginProxyController.login(httpServletRequest, username, password, null);
        /*if (proxy.isSuccess()) {*/
        if(true) {
			// 获取Shiro管理的Session
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession();
			Member member = memberService.doLoginCheck(username, password);
			// Shiro添加会话
			session.setAttribute("username", username);
			session.setAttribute(org.easymis.commons.web.Constants.SESSION_USER, member);
			// 删除验证码Session
			session.removeAttribute(org.easymis.commons.web.Constants.SESSION_SECURITY_CODE);
			// 保存登录IP
			getRemortIP(username);
			//保存員工信息
			HrmStaffInfo staff=staffInfoMng.findByMemberAndOrganize(member.getMemberId(), null);
			session.setAttribute("staffId", staff.getStaffId());
			session.setAttribute("staffName", staff.getName());
			session.setAttribute(org.easymis.commons.web.Constants.SESSION_STAFF, staff);							
			/** Shiro加入身份验证 **/
			Subject sub = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			sub.login(token);
	
			json.setSuccess(true);
			json.setMsg("登录成功");
			return json;
        }
        else {
            // map.put("error", proxy.getResult());
           // json.setMsg(proxy.getResult());
        }
        return json;
    }
    @ApiOperation(value = "退出系统 ",notes = "",produces = MediaType.TEXT_HTML_VALUE)
    @RequestMapping(value = "/common/login_do/loginout.do",method = RequestMethod.GET)
    public String loginout(HttpServletRequest request,HttpServletResponse response){
/*        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }*/
        return "redirect:/common/login_do/tologin.do";
    }
    @ApiOperation(value = "登录页面",notes = "",produces = MediaType.TEXT_HTML_VALUE)
    @RequestMapping(value = { "/common/login_do/tologin.do", "/" },method = { RequestMethod.GET, RequestMethod.POST })
    public String tologin(ModelMap map){
        map.put("icp", SystemConstant.getICP());
        map.put("systemname", SystemConstant.getSystemName());
        map.put("systemdomain", SystemConstant.getSystemdomain());
        return "/login";
    }
}
